package com.example.demo.mqttIntegration;

/**
 * @Author: Pinp
 * @Date: 2021/9/10 13:40
 */

import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;

/**
 * mqtt消息处理配置
 */
@Configuration
@ConditionalOnProperty(value = "mqtt.enabled", havingValue = "true")
public class MqttBaseConfig {

    @Value("${mqtt.client_id:mqtt_client}")
    private String clientId;

    private String willTopic = "lwt";

    /**
     * 构造一个默认的mqtt客户端操作bean
     *
     * @return
     */
    @Bean
    public MqttPahoClientFactory factory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions options = new MqttConnectOptions();
        options.setServerURIs(new String[] {"tcp://47.242.90.7:1885"});
        options.setUserName("user");
        options.setPassword("user0110".toCharArray());
        options.setCleanSession(true);
        options.setKeepAliveInterval(10);
        options.setWill(willTopic, clientId.getBytes(), 1, false);
        options.setAutomaticReconnect(true);
        options.setConnectionTimeout(15);
        factory.setConnectionOptions(options);
        return factory;
    }

}


